module jinji.link.api;

import jinji.common.query,
jinji.common.type,
jinji.link.model,
jinji.link.service;

extern (C):

mixin getObject!(Link, "getLink", "查询链接", "链接", "url");

//mixin getObject!(LinkAlias, "getLinkAlias", "查询链接别名", "链接别名", "pattern");

/// 获取指向指定内容的链接
@"链接数组"@type("string[]")
@Action void linksOf(ref Request req, @"hash值"@type("Uint8Array") Hash hash,
	@"排序方式" string order = "size desc", @"偏移量"int offset = 0, @"最大结果数"int limit = 3) {
	if (limit > 3)
		uid(req);
	enum sql = SB.select!(Link.url).where("hash=$1");
	foreach (row; query(sql.orderByCE(order)
			.limit("$2").offset("$3"), hash[], min(limit, 5), offset))
		req.send(row.get!string);
}

/// 反馈链接状态
@"影响行数"@type("[number]")
@Action void setLink(ref Request req, @"URL" string url, @"状态"int status) {
	checkArgRange(status.stringof, LinkStatus.min <= status && status <= LinkStatus.max, "无效的状态");
	req.require(status == LinkStatus.flagged ? Perm.none : Perm.post);

	auto q = query!(SB.select!(Link.status).where("url=$1"))(url);
	checkArg(url.stringof, !q.empty, "链接不存在");

	int r;
	const s = q.get!LinkStatus;
	if (s != status)
		r += exec!(SB.update!Link.set("status=$1").where("url=$2"))(status, url);
	req.send(r);
}

/// 添加/修改/删除链接别名
@"删除数量"@type("[number]")
@Action void setLinkAlias(ref Request req, @"ID"long id, @"查找内容" string pattern,
	@"替换内容" string substitute, @"描述" string desc = "") {
	req.require(Perm.editLA);
	req.modify!LinkAlias(parseId(id), parseText!"查找内容"(pattern, 256),
		parseText!"替换内容"(substitute, maxDescLength), parseDesc(desc), req.uid, now);
}

/// 解析链接别名
@"链接"@type("[string]")
@Action void resolveLink(ref Request req, @"链接" string url) {
	// TODO
	req.send(normalizeLink(url, req.uid));
}
